<!-- 头像 -->
<template>
  <div class="uploadAvatar-container" ref="uploadAvatar">
    <input type="file" @change="changeImg($event)" accept="image/*" class="file" />
    <Icon type="plus" />
    <img ref="img" :src="imgPath" alt="" class="preview" />
  </div>
</template>

<script setup>
import { ref } from "vue";
import Icon from "@/components/Icon/index.vue"
const imgPath = ref();
const img = ref(null)
const uploadAvatar = ref(null)
const emit = defineEmits(["click"])
function changeImg(e) {
  const avatar = e.target.files[0];
  if (avatar) {
    // 解析为base64格式
    const reader = new FileReader();
    reader.onload = (e) => {
      imgPath.value = e.target.result;
    };
    reader.readAsDataURL(avatar);
    uploadAvatar.value.style.border = 0
    img.value.style.opacity = 1
    emit("click",avatar)
  } else {
    return
  }
}
// 清除图片
const close = () => {
  imgPath.value = ""
  uploadAvatar.value.style.border = "2px dashed #b4b8bc"
  img.value.style.opacity = 0
}
defineExpose({
  close
})


</script>

<style lang="less" scoped>
@import "@/styles/var.less";
@import "@/styles/mixin.less";
.uploadAvatar-container {
  width: 100%;
  height: 100%;
  position: relative;
  border: 2px dashed @gray;
  border-radius: 5px;
  overflow: hidden;
  &:hover,
  &:hover .icon-container{
    border-color:@frameColor1;
    color: @frameColor1;
  }

  .file{
    position: absolute;
    left: -50%;
    top: -50%;
    z-index: 99;
    opacity: 1;
    width: 150%;
    height: 150%;
    outline: none;
    cursor: pointer;
    
  }
  .preview {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
  }
  .icon-container{
    .self-center();
    font-size: 35px;
    color: @gray;
  }
}
</style>